#!/usr/bin/python
from bottle import route,run,get,post,response,static_file,request
import cv2,cv
import thread
import base64
#import carcontrol module
from controlServer import *

cam=cv2.VideoCapture(0)
if(cam.isOpened()==False):
	print("cant open cam")
	exit()
cam.set(cv.CV_CAP_PROP_FRAME_WIDTH,320)
cam.set(cv.CV_CAP_PROP_FRAME_HEIGHT,240)
gimg=''
#get image from cam
def img_thread():
	global cam
	global gimg
	while True:
		ret,gimg=cam.read()
#respone image for ajax by base64 string
@get('/getImg')
def get_img2ba_base64():
	global gimg
	jpg_img=cv2.imencode(".jpeg",gimg)[1].tostring()
	encoded_str=base64.b64encode(jpg_img)
	return encoded_str
#control rccar
@post('/rccar')
def control_rccar():
	cmd=request.forms.get('cmd')
	print cmd
	if cmd == "GO":
		forward()
	elif cmd == "LEFT":
		left()
	elif cmd == "STOP":
		stop()
	elif cmd == "RIGHT":
		right()
   	elif cmd == "BACK":
		backward()
	return ''


@route('/')
def do_route():
	return static_file("index.html",root=".")

thread.start_new_thread(img_thread,())
run(host='192.168.0.14', port=8080)
